<template>
  <div class="home-container">
    <!-- 顶部导航 -->
    <TopNav />

    <!-- 自定义轮播图 -->
    <div class="carousel">
      <!-- 图片轮播 -->
      <div class="carousel-images">
        <img :src="currentImage" alt="轮播图" />
      </div>

      <!-- 控制按钮 -->
      <div class="carousel-controls">
        <button @click="prev">&#10094;</button>
        <button @click="next">&#10095;</button>
      </div>

      <!-- 指示器 -->
      <div class="indicators">
        <span
          v-for="(banner, index) in banners"
          :key="index"
          :class="{ active: index === currentIndex }"
          @click="goTo(index)"
        ></span>
      </div>
    </div>

    <!-- 商品展示区域 - 热门商品 -->
    <div class="goods-section">
      <h2>热门商品</h2>

      <!-- 横向滚动容器 -->
      <div class="goods-carousel">
        <!-- 左右箭头 -->
        <button class="carousel-control prev" @click="scrollCarousel('prev')">&#10094;</button>
        <div class="goods-list">
          <el-card
            class="good-card"
            v-for="good in goodsList"
            :key="good.id"
            @click="goToDetail(good)"
          >
            <div class="good-image">
              <img :src="good.gImage" alt="商品图片" />
            </div>
            <div class="good-info">
              <h3>{{ good.gName }}</h3>
              <p>{{ good.gDesciption || '暂无描述' }}</p>
              <p style="color: #e60012;">￥{{ good.gPrice }}</p>
            </div>
          </el-card>
        </div>
        <button class="carousel-control next" @click="scrollCarousel('next')">&#10095;</button>
      </div>
    </div>

    <!-- 商品展示区域 - 非热销商品 -->
    <div class="goods-section">
      <h2>其他商品</h2>

      <!-- 两列布局 -->
      <div class="two-column-grid">
        <el-card
          class="good-card"
          v-for="good in notHotGoodsList"
          :key="good.id"
          @click="goToDetail(good)"
        >
          <div class="good-image">
            <img :src="good.gImage" alt="商品图片" />
          </div>
          <div class="good-info">
            <h3>{{ good.gName }}</h3>
            <p>{{ good.gDesciption || '暂无描述' }}</p>
            <p style="color: #e60012;">￥{{ good.gPrice }}</p>
          </div>
        </el-card>
      </div>
    </div>

    <footer-bar />
  </div>
</template>
<script>
import TopNav from '@/components/TopNav.vue'
import FooterBar from '@/components/FooterBar.vue'
import goodApi from '@/api/user.js'
import searchApi from '@/api/search'
import { useRouter } from 'vue-router'

// 引入本地图片
import banner1 from '@/assets/images/lanmei.jpg'
import banner2 from '@/assets/images/niupai.jpg'
import banner3 from '@/assets/images/niurou.jpg'
import banner4 from '@/assets/images/xihongshi.jpg'
import banner5 from '@/assets/images/qincai.jpg'

export default {
  name: 'HomeView',
  components: { TopNav, FooterBar },
  data() {
    return {
      // 轮播图数据
      banners: [banner1, banner2, banner3, banner4, banner5],
      currentIndex: 0,
      interval: null,

      // 热门商品数据
      goodsList: [],
      loading: false,

      // 非热销商品数据
      notHotGoodsList: [],
      notHotLoading: false
    }
  },
  computed: {
    currentImage() {
      return this.banners[this.currentIndex]
    }
  },
  mounted() {
    this.startAutoPlay()
    this.getGoodListPage()
    this.getNotHotGoodList()
  },
  beforeUnmount() {
    this.stopAutoPlay()
  },
  methods: {
    // 轮播自动播放控制
    startAutoPlay() {
      this.interval = setInterval(() => {
        this.next()
      }, 3000)
    },
    stopAutoPlay() {
      clearInterval(this.interval)
    },
    resetAutoPlay() {
      this.stopAutoPlay()
      this.startAutoPlay()
    },

    // 手动切换逻辑
    prev() {
      this.currentIndex = (this.currentIndex - 1 + this.banners.length) % this.banners.length
      this.resetAutoPlay()
    },
    next() {
      this.currentIndex = (this.currentIndex + 1) % this.banners.length
      this.resetAutoPlay()
    },
    goTo(index) {
      this.currentIndex = index
      this.resetAutoPlay()
    },

    // 获取热门商品列表
    async getGoodListPage() {
      this.loading = true
      try {
        const res = await goodApi.getHotGoods()
        if (res && res.code === 200) {
          this.goodsList = res.data
        } else {
          this.$message.error('获取热门商品失败')
        }
      } catch (error) {
        console.error(error)
        this.$message.error('请求失败，请检查网络')
      } finally {
        this.loading = false
      }
    },

    // 获取非热销商品列表
    async getNotHotGoodList() {
      this.notHotLoading = true
      try {
        const res = await goodApi.getNotHotGoods()
        if (res && res.code === 200) {
          this.notHotGoodsList = res.data
        } else {
          this.$message.error('获取非热销商品失败')
        }
      } catch (error) {
        console.error(error)
        this.$message.error('请求失败，请检查网络')
      } finally {
        this.notHotLoading = false
      }
    },

    // 滚动热门商品区域
    scrollCarousel(direction) {
      const goodsList = this.$el.querySelector('.goods-list:nth-of-type(1)')
      const cardWidth = this.$el.querySelector('.good-card').offsetWidth + 20

      if (direction === 'next') {
        goodsList.scrollLeft += cardWidth
      } else if (direction === 'prev') {
        goodsList.scrollLeft -= cardWidth
      }
    },

    // 跳转到商品详情页
   goToDetail(good) {
  const { id } = good

  searchApi.getGoodMatchById(id).then(response => {
    if (response && response.code === 200 && response.data && response.data.id) {
      // ✅ 正确使用 this.$router
      this.$router.push({ name: 'GoodsDetail', params: { id: response.data.id } })
    } else {
      alert('商品不存在或接口返回异常')
    }
  }).catch(error => {
    console.error('调用接口失败:', error)
    alert('网络异常，请重试')
  })
}
  }
}
</script>
<style scoped>
.home-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

/* 全宽轮播图 */
.carousel {
  position: relative;
  width: 100%;
  max-width: 100%;
  margin: 20px auto;
  margin-top: 20px;
  overflow: hidden;
  border-radius: 8px;
  height: 400px;
}

.carousel-images {
  width: 100%;
  height: 100%;
  margin: 0 auto;
  position: relative;
}

.carousel-images img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.carousel-controls button {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  padding: 10px;
  cursor: pointer;
  font-size: 18px;
  z-index: 2;
}

.carousel-controls button:hover {
  background-color: rgba(0, 0, 0, 0.8);
}

.carousel-controls button:first-child {
  left: 20px;
}

.carousel-controls button:last-child {
  right: 20px;
}

.indicators {
  text-align: center;
  position: absolute;
  bottom: 10px;
  left: 0;
  right: 0;
}

.indicators span {
  display: inline-block;
  width: 10px;
  height: 10px;
  margin: 0 5px;
  background-color: #bbb;
  border-radius: 50%;
  cursor: pointer;
}

.indicators span.active {
  background-color: #fff;
}

.goods-section {
  padding: 20px;
  background-color: #f9f9f9;
  flex: 1;
}

.goods-carousel {
  position: relative;
  overflow: hidden;
  margin-top: 20px;
}

.goods-list {
  display: flex;
  gap: 20px;
  overflow-x: auto;
  padding-bottom: 20px;
  scroll-behavior: smooth;
}

.two-column-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.good-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.good-card:hover {
  transform: translateY(-5px);
}

.good-image {
  width: 100%;
  height: 180px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.good-image img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.good-info {
  padding: 10px;
  text-align: center;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.carousel-control {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  padding: 10px;
  cursor: pointer;
  font-size: 18px;
  z-index: 2;
}

.carousel-control:hover {
  background-color: rgba(0, 0, 0, 0.8);
}

.carousel-control.prev {
  left: 20px;
}

.carousel-control.next {
  right: 20px;
}
</style>